include ../Makefile

.DEFAULT_GOAL		= app

CONFIG_BATCH    	?= 

CONFIG_ITRACE   	?=
CONFIG_VTRACE   	?=
CONFIG_DIFFTEST 	?= 1
CONFIG_WATCHPOINT 	?= 
CONFIG_DETECT		?= 

CONFIG_DEVICE   	?= 1
CONFIG_DISPLAY 		?= 1
CONFIG_KEYBOARD 	?= 1
CONFIG_CLINT		?=

APP = npc-riscv64
TOP = top
VERILATOR = verilator

BUILD_DIR = $(NPC_HOME)/build
OBJ_DIR = $(BUILD_DIR)/obj_dir
BINARY = $(BUILD_DIR)/$(APP)
VSRC_DIR = $(NPC_HOME)/vsrc
CSRC_DIR = $(NPC_HOME)/csrc

VFLAGS = -MMD --build -cc -O3 --x-assign fast \
         --x-initial fast --noassert -Wall  \
         -y $(abspath $(VSRC_DIR)) \
         $(if $(CONFIG_VTRACE),--trace,)

default: $(BINARY)

$(shell mkdir -p $(BUILD_DIR))

# project source
VSRCS = $(shell find $(abspath $(VSRC_DIR)) -maxdepth 6 -name "*.v" -or -name "*.sv")
CSRCS = $(shell find $(abspath $(CSRC_DIR)) -maxdepth 6 -name "*.c" -or -name "*.cc" -or -name "*.cpp")

CFLAGS += -I$(OBJ_DIR) -I$(CSRC_DIR)/include \
		  $(if $(CONFIG_DEVICE),$(shell sdl2-config --cflags),)  \
		  $(if $(CONFIG_ITRACE),-DCONFIG_ITRACE=1,)  \
		  $(if $(CONFIG_VTRACE),-DCONFIG_VTRACE=1,)  \
		  $(if $(CONFIG_DIFFTEST),-DCONFIG_DIFFTEST=1,) \
		  $(if $(CONFIG_DISPLAY),-DCONFIG_DISPLAY=1,) \
		  $(if $(CONFIG_KEYBOARD),-DCONFIG_KEYBOARD=1,) \
		  $(if $(CONFIG_CLINT),-DCONFIG_CLINT=1,) \
		  $(if $(CONFIG_WATCHPOINT),-DCONFIG_WATCHPOINT=1,) \
		  $(if $(CONFIG_DETECT),-DCONFIG_DETECT=1,) \
		  -DCONFIG_ISA64=1

LDFLAGS = -lreadline $(if $(CONFIG_DEVICE),$(shell sdl2-config --libs),) \

$(BINARY): $(VSRCS) $(CSRCS)
	@rm -rf $(OBJ_DIR)
	$(VERILATOR) $(VFLAGS) \
		--top-module $(TOP) $^ \
		$(addprefix -CFLAGS , $(CFLAGS)) $(addprefix -LDFLAGS , $(LDFLAGS)) \
		--Mdir $(OBJ_DIR) \
		--exe -o $(abspath $(BINARY)) \
		--Wall

ARGS_DIFF ?= $(if $(CONFIG_DIFFTEST), --ref=$(shell pwd)/spike-diff/build/spike-ref-so,)
ARGS_LOG ?= --log=$(BUILD_DIR)/log
ARGS_IMG ?=
ARGS_BATCH ?= $(if $(CONFIG_BATCH), -b,)

ARGS = $(ARGS_LOG) $(ARGS_IMG) $(ARGS_BATCH) $(ARGS_DIFF)

NPC_EXEC := $(BINARY) $(ARGS)

.PHONY: app clean

app: $(BINARY)

sim run: $(BINARY)
	$(call git_commit, "sim RTL")
	$(NPC_EXEC)

gdb-remote: $(BINARY)
	$(call git_commit, "debug RTL")
	gdbserver :1234 $(NPC_EXEC)

clean:
	rm -rf $(BUILD_DIR) $(LOG_DIR)

.PHONY: default clean run
